﻿using System;
using System.Collections.Generic;
using System.Resources;
using System.Text;
using System.Reflection;

namespace ArgusPCLib
{
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum, AllowMultiple=false, Inherited=false)]
	public class LocalizableObjectAttribute : Attribute
	{
		public string NamePrefix { get; private set; }
		public string DescriptionPrefix { get; private set; }
		public ResourceManager ResourceManager{get;private set;}

		public LocalizableObjectAttribute(string assemblyName, string resourceManagerBasename, string namePrefix, string descriptionPrefix)
			: base()
		{
			this.NamePrefix = namePrefix;
			this.DescriptionPrefix = descriptionPrefix;
			if (string.IsNullOrEmpty(assemblyName) || string.IsNullOrEmpty(resourceManagerBasename))
				return;

			Assembly assembly = Assembly.Load(new AssemblyName(assemblyName));
			if (assembly == null)
				return;

			this.ResourceManager = new ResourceManager(resourceManagerBasename, assembly);
		}

		public string GetLocalizedName(object value)
		{
			if (value == null || this.ResourceManager == null || this.NamePrefix == null)
				return null;

			string key = value.ToStringInvariant();
			if (string.IsNullOrEmpty(key))
				return null;

			return this.ResourceManager.GetString(this.NamePrefix + key);
		}

		public string GetLocalizedDescription(object value)
		{
			if (value == null || this.ResourceManager == null || this.DescriptionPrefix == null)
				return null;

			string key = value.ToStringInvariant();
			if (string.IsNullOrEmpty(key))
				return null;

			return this.ResourceManager.GetString(this.DescriptionPrefix + key);
		}

		public static LocalizableObjectAttribute FromObject(object value)
		{
			Type type = value.GetType();
			return type.GetTypeInfo().GetCustomAttribute<LocalizableObjectAttribute>(false);
		}
	}
}
